package com.think.admin.oauth.config;

import com.think.admin.cons.AdminCons;
import com.think.admin.oauth.handle.OauthAuthenticationEntryPointImpl;
import com.think.admin.oauth.handle.WebResponseExceptionTranslatorImpl;
import com.think.admin.oauth.integration.IntegrationAuthenticationFilter;
import com.think.admin.oauth.integration.IntegrationAuthenticationService;
import com.think.admin.oauth.redis.CustomRedisTokenStore;
import lombok.RequiredArgsConstructor;
import org.redisson.spring.data.connection.RedissonConnectionFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;

/**
 * <p>
 * 授权服务器配置
 * </p>
 *
 * @author xwj
 * @date 2019/4/24
 */
@Configuration
@EnableAuthorizationServer
@RequiredArgsConstructor
public class Oauth2AuthorizationServer extends AuthorizationServerConfigurerAdapter {
    private final IntegrationAuthenticationService integrationAuthenticationService;
    private final AuthenticationManager authenticationManager;
    private final RedissonConnectionFactory redissonConnectionFactory;
    private final WebResponseExceptionTranslatorImpl webResponseExceptionTranslator;
    private final OauthAuthenticationEntryPointImpl oauthAuthenticationEntryPoint;

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
        oauthServer
                // 允许所有资源服务器访问公钥端点（/oauth/token_key）
                .tokenKeyAccess("permitAll()")
                // 只允许验证用户访问令牌解析端点（/oauth/check_token）
                .checkTokenAccess("isAuthenticated()")
                // 允许客户端发送表单来进行权限认证来获取令牌
                .allowFormAuthenticationForClients()
                .authenticationEntryPoint(oauthAuthenticationEntryPoint)
                .addTokenEndpointAuthenticationFilter(new IntegrationAuthenticationFilter());
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints
                // 身份认证管理器, 用于"password"授权模式
                .authenticationManager(authenticationManager)
                .userDetailsService(integrationAuthenticationService)
                // 采用redis储存
                .tokenStore(new CustomRedisTokenStore(redissonConnectionFactory))
                // 自定义异常
                .exceptionTranslator(webResponseExceptionTranslator);
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory().withClient("think-view")
                .secret(new BCryptPasswordEncoder().encode("think-view"))
                // 令牌有效时间
                .accessTokenValiditySeconds(AdminCons.Param.TOKEN_TIME_OUT)
                .refreshTokenValiditySeconds(AdminCons.Param.REFRESH_TOKEN_TIME_OUT)
                // 支持刷新令牌，密码授权模式
                .authorizedGrantTypes("refresh_token", "password")
                .scopes("all");
    }
}